﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.IO;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.Xml.Linq;
using CodeCarvings.Piczard.Filters.Watermarks;
using System.Web.Services;

namespace Framework.WebmasterTool
{
    public partial class Categories : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

		protected void Page_Load(object sender, EventArgs e)
		{
			siuCateImage.ImageRemove += new EventHandler(siuCateImage_ImageRemove);
			siuCateImage.ImageUpload += new SimpleImageUpload.ImageUploadEventHandler(siuCateImage_ImageUpload);
			if (!IsPostBack)
			{
				CheckPermission();
				//CleanImageUploadTemp();
				CallImageUpload();
				LoadCateDDL();
				LoadCateTRV();
				ExpandAllNode();
				LoadCateDetails();
			}
		}

		public void CheckPermission()
		{
			MembershipUser someUser = Membership.GetUser();
			if (someUser == null)
			{
				Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
			}
			bool flag = false;
			var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
			user.aspnet_Roles.Load();
			var rolesForUser = user.aspnet_Roles.ToList();
			foreach (var item in rolesForUser)
			{
				var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
				if (permission.Category.Value == true)
				{
					flag = true;
				}
			}
			if (flag == false)
			{
				lblPermissionMessage.Visible = true;
				Panel1.Visible = false;
			}
		}

		void siuCateImage_ImageRemove(object sender, EventArgs e)
		{
			chkWatermarkImage.Enabled = true;
		}

		void siuCateImage_ImageUpload(object sender, SimpleImageUpload.ImageUploadEventArgs args)
		{
			chkWatermarkImage.Enabled = false;
		}

		public void CleanImageUploadTemp()
		{
			foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
			{
				File.Delete(file);
			}
		}

		public void ImageUpload(SimpleImageUpload ctrImageUpload)
		{
			ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
			ctrImageUpload.CropConstraint = new FreeCropConstraint();
			ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
			ctrImageUpload.Text_BrowseButton = "Upload ảnh";
			ctrImageUpload.Text_CancelUploadButton = "Huỷ";
			ctrImageUpload.Text_EditButton = "Sửa ảnh";
			ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
		}

		public void CallImageUpload()
		{
			ImageUpload(siuCateImage);
		}

		public void LoadCateDDL()
		{
			string levels = "|---";
			string spaces = "&nbsp;";
			List<udv_Categories> allCate = entity.udv_Categories.ToList();
			List<udv_Categories> cateBannerParent = allCate.Where(ca => ca.ParentID == 0).ToList();
			foreach (var item in cateBannerParent)
			{
				ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
				LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
			}
		}

		public void LoadSubCateDDL(ref List<udv_Categories> allCate, int cateParentID, ref string spaces, string levels)
		{
			List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
			foreach (var item in subCateBanner)
			{
				ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
				if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
				{
					spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
					LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
				}
			}
			if (spaces.Length > 6)
				spaces = spaces.Substring(0, spaces.Length - 36);
		}

		public TreeNode FindNode(string value, TreeNodeCollection nodes)
		{
			foreach (TreeNode n in nodes)
			{
				if (n.Value == value)
				{
					return n;
				}
				else // search n's child nodes
				{
					TreeNode nChild = FindNode(value, n.ChildNodes);
					if (nChild != null)
						return nChild;
				}
			}
			return null;
		}

		public void ExpandNode(string NootValue)
		{
			TreeNode n = FindNode(NootValue, trvCategories.Nodes);
			while (n != null)
			{
				n.Expand();
				n = n.Parent;
			}
		}

		public void ExpandAllNode()
		{
			List<udv_Categories> cateParent = entity.udv_Categories.Where(ca => ca.ParentID == 0).ToList();
			foreach (var item in cateParent)
			{
				ExpandNode(item.CateID.ToString());
			}
		}

		public void PopulateCategoriesNode(TreeNode n, List<udv_Categories> allCate)
		{
			List<udv_Categories> menuChild = allCate.Where(ca => ca.ParentID == int.Parse(n.Value)).ToList();
			if (menuChild.Count == 0)
			{
				return;
			}
			else
			{
				foreach (var item in menuChild)
				{
					TreeNode treeNodeChild = new TreeNode(item.Title, item.CateID.ToString());
					treeNodeChild.Collapse();
					treeNodeChild.NavigateUrl = Globals.ApplicationPath + "WebmasterTool/Categories.aspx?CateID=" + item.CateID;
					n.ChildNodes.Add(treeNodeChild);
					PopulateCategoriesNode(treeNodeChild, allCate);
				}
			}
		}

		public void LoadCateTRV()
		{
			trvCategories.Nodes.Clear();

			List<udv_Categories> allCate = entity.udv_Categories.ToList();

			var cateParent = allCate.Where(ca => ca.ParentID == 0).ToList();

			if (cateParent.Count != 0)
			{
				foreach (var item in cateParent)
				{
					TreeNode treeNodeParent = new TreeNode(item.Title, item.CateID.ToString());
					treeNodeParent.NavigateUrl = Globals.ApplicationPath + "WebmasterTool/Categories.aspx?CateID=" + item.CateID;
					trvCategories.Nodes.Add(treeNodeParent);
					var cateChild = allCate.Where(ca => ca.ParentID == item.CateID);
					foreach (var subItem in cateChild)
					{
						TreeNode treeNodeChild = new TreeNode(subItem.Title, subItem.CateID.ToString());
						treeNodeChild.NavigateUrl = Globals.ApplicationPath + "WebmasterTool/Categories.aspx?CateID=" + subItem.CateID;
						treeNodeParent.ChildNodes.Add(treeNodeChild);
						PopulateCategoriesNode(treeNodeChild, allCate);
						trvCategories.ExpandAll();
					}
				}
			}
		}

		public void LoadCateDetails()
		{
			if (Request.QueryString["CateID"] != null)
			{
				int cateID;
				int.TryParse(Request.QueryString["CateID"], out cateID);
				if (cateID == ConfigPaths.Category_Article_ID)
				{
					ddlCategories.SelectedValue = ConfigPaths.Category_Article_ID.ToString();
				}
				else if (cateID == ConfigPaths.Category_Product_ID)
				{
					ddlCategories.SelectedValue = ConfigPaths.Category_Product_ID.ToString();
				}
				else if(cateID == ConfigPaths.Category_Video_ID)
				{
					ddlCategories.SelectedValue = ConfigPaths.Category_Video_ID.ToString();
				}
				else if (cateID == ConfigPaths.Category_Photo_ID)
                {
                    ddlCategories.SelectedValue = ConfigPaths.Category_Photo_ID.ToString();
                }
				var cateByID = entity.udv_Categories.Where(ca => ca.CateID == cateID).FirstOrDefault();
				if (cateByID != null)
				{
					LoadListImageCate(cateByID.CateID);
					ddlCategories.SelectedValue = cateByID.ParentID.ToString();
					if (cateByID.Remove == false)
					{
						ddlCategories.Enabled = false;
						txtCateName.Enabled = false;
						btnNew.Visible = true;
					}
					else
					{
						btnNew.Visible = btnDelete.Visible = true;
					}
					txtCateName.Text = cateByID.Title.Trim();
					txtCateName_en.Text = cateByID.Title_en.Trim();
					txtExternalLink.Text = string.IsNullOrEmpty(cateByID.ExternalLink) ? string.Empty : cateByID.ExternalLink.Trim();
					chkBlankExternalLink.Checked = cateByID.BlankExternalLink == null ? false : cateByID.BlankExternalLink.Value;
					txtDesciption.Text = cateByID.Description;
					txtDesciption_en.Text = cateByID.Description_en;
					txtMetaDescription.Text = cateByID.MetaDescription.Trim();
					txtMetaKeywords.Text = cateByID.MetaKeywords.Trim();
                    txtMetaTitle.Text = cateByID.MetaTitle.Trim();
                    txtMetaOrther.Text = HttpUtility.HtmlDecode(cateByID.MetaOrther.Trim());
					if (cateByID.ImageUrl != null && cateByID.ImageUrl.Trim() != "")
					{
						string sourceImageFilePath = ConfigPaths.Path_ImageCategories_Folder_MapPath + cateByID.ImageUrl;
						siuCateImage.LoadImageFromFileSystem(Server.MapPath(sourceImageFilePath));
						chkWatermarkImage.Enabled = false;
					}
					txtImageAlt.Text = cateByID.ImageAlt.Trim();
					txtCateOrder.Text = cateByID.DisplayOrder.ToString();
					chkIsActive.Checked = cateByID.IsActive.Value;
                    chkIsActiveBottom.Checked = cateByID.IsMenuBottom.Value;
					chkCateTop.Checked = cateByID.IsTop.Value;
					txtPaging.Text = cateByID.PagingSize.ToString();
					lblAddedDate.Text = String.Format("{0:dd/MM/yyyy}", cateByID.AddedDate);
					lblAddedBy.Text = cateByID.AddedBy;
					lblUpdatedDate.Text = String.Format("{0:dd/MM/yyyy}", cateByID.UpdatedDate);
					lblUpdatedBy.Text = cateByID.UpdatedBy;
				}
				else
				{
					lblMsg.Text = "Danh mục đang chọn không tồn tại";
					lblMsg.ForeColor = System.Drawing.Color.Red;
				}
			}
		}

		protected void btnNew_Click(object sender, EventArgs e)
		{
			Response.Redirect("Categories.aspx");
		}

		public void AddAllCateDelete(ref List<udv_Categories> allCate, int cateParentID, ref List<udv_Categories> allCateDelete)
		{
			List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
			foreach (var item in subCateBanner)
			{
				allCateDelete.Add(item);
				if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
				{
					AddAllCateDelete(ref allCate, item.CateID, ref allCateDelete);
				}
			}
		}

		protected void btnDelete_Click(object sender, EventArgs e)
		{
			if (Request.QueryString["CateID"] != null)
			{
				int cateID;
				int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
				var allCate = entity.udv_Categories.ToList();
				var cateDelete = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
				if (cateDelete != null)
				{
					List<udv_Categories> allCateDelete = new List<udv_Categories>();
					AddAllCateDelete(ref allCate, cateDelete.CateID, ref allCateDelete);
					allCateDelete.Add(cateDelete);
					allCateDelete = allCateDelete.OrderByDescending(ca => ca.ParentID).ToList();
					foreach (var item in allCateDelete)
					{
						List<udv_Images> listCateImage = entity.udv_Images.Where(ic => ic.udv_Categories.CateID == item.CateID).ToList();
						foreach (var subItem in listCateImage)
						{
							Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + subItem.ImageUrl));
						}
						List<udv_Files> listCateFile = entity.udv_Files.Where(fi => fi.udv_Categories.CateID == item.CateID).ToList();
						foreach (var subItem in listCateFile)
						{
							Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_FileDownload_Folder_MapPath + subItem.FileURL));
						}
						Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + item.ImageUrl));
						string urlRewriteCategoryOld = Globals.CreateUrlRewriteCategory(ref entity, item.CateID, true) + DGSFramework.Globals.GetUrlRewriteExtension();
						Globals.DeleteROR("~/ror.xml", urlRewriteCategoryOld);
						Globals.DeleteSiteMap("~/sitemap.xml", urlRewriteCategoryOld);
						Globals.DeleteUrlList("~/urllist.txt", urlRewriteCategoryOld);

                        //create db log
                        CreateDBLog(null, null, TypeAction.Delete, "Xoá danh mục: " + item.Title, item.Description, "", "", "",
                            item.IsActive.Value.ToString(), item.IsTop.Value.ToString(), item.MetaKeywords, item.MetaDescription);

						entity.DeleteObject(item);
						entity.SaveChanges();
					}
					//data cache
					Cache.Remove("Category");
					//clear outputcache
					HttpResponse.RemoveOutputCacheItem("/Default.aspx");
					HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
					HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
					HttpResponse.RemoveOutputCacheItem("/Products.aspx");
					HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
					HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
					Response.Redirect("Categories.aspx");
				}
				else
				{
					lblMsg.Text = "Danh mục muốn xoá không tồn tại";
					lblMsg.ForeColor = System.Drawing.Color.Red;
				}
			}
			else
			{
				lblMsg.Text = "Danh mục muốn xoá không tồn tại";
				lblMsg.ForeColor = System.Drawing.Color.Red;
			}
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			List<string> listImageNameUpload = UploadAndGetImageName();
			List<string> listImageTitle = new List<string>();
			List<string> listImageTitle_en = new List<string>();
			List<string> listImageAlt = new List<string>();
			if (listImageNameUpload.Count > 0)
			{
				listImageTitle = GetImageTitle();
				listImageTitle_en = GetImageTitle_en();
				listImageAlt = GetImageAlt();
			}
			if (Request.QueryString["CateID"] == null)
			{
				udv_Categories cateInsert = new udv_Categories();
				cateInsert.AddedDate = DateTime.Now;
				cateInsert.UpdatedDate = DateTime.Now;
				cateInsert.AddedBy = Membership.GetUser().UserName;
				cateInsert.UpdatedBy = Membership.GetUser().UserName;
				cateInsert.Remove = true;
				cateInsert.Title = txtCateName.Text.Trim();
				cateInsert.Title_en = txtCateName_en.Text.Trim();
				cateInsert.ExternalLink = txtExternalLink.Text.Trim();
				cateInsert.BlankExternalLink = chkBlankExternalLink.Checked;
				cateInsert.Description = txtDesciption.Text;
				cateInsert.Description_en = txtDesciption_en.Text;
				if (siuCateImage.HasImage == true)
				{
					string fileNameImage = Globals.GetFileName(siuCateImage.SourceImageClientFileName);
					siuCateImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageCategories_Folder + fileNameImage);
					cateInsert.ImageUrl = fileNameImage;
				}
				else
				{
					cateInsert.ImageUrl = "";
				}
				cateInsert.ImageAlt = txtImageAlt.Text.Trim();
				cateInsert.DisplayOrder = int.Parse(txtCateOrder.Text);
				cateInsert.ParentID = int.Parse(ddlCategories.SelectedValue);
				cateInsert.IsActive = chkIsActive.Checked;
                cateInsert.IsMenuBottom = chkIsActiveBottom.Checked;
				cateInsert.IsTop = chkCateTop.Checked;
				cateInsert.MetaDescription = txtMetaDescription.Text;
				cateInsert.MetaKeywords = txtMetaKeywords.Text;
                cateInsert.MetaTitle = txtMetaTitle.Text;
                cateInsert.MetaOrther = HttpUtility.HtmlEncode(txtMetaOrther.Text);
				cateInsert.PagingSize = int.Parse(txtPaging.Text);
				entity.AddToudv_Categories(cateInsert);
				entity.SaveChanges();
				if (listImageNameUpload.Count > 0)
				{
					for (int i = 0; i < listImageNameUpload.Count; i++)
					{
						udv_Images imageCate = new udv_Images();
						imageCate.udv_Categories = cateInsert;
						imageCate.ImageUrl = listImageNameUpload[i];
						imageCate.ImageAlt = listImageAlt[i];
						imageCate.Title = listImageTitle[i];
						imageCate.Title_en = listImageTitle_en[i];
						imageCate.Description = "";
						imageCate.Description_en = "";
						imageCate.AddedDate = DateTime.Now;
						entity.AddToudv_Images(imageCate);
						entity.SaveChanges();
					}
				}
				string urlRewriteCategory = Globals.CreateUrlRewriteCategory(ref entity, cateInsert.CateID, true);
				cateInsert.UrlRewrite = urlRewriteCategory;
				entity.SaveChanges();
				Globals.CreateROR("~/ror.xml", urlRewriteCategory + DGSFramework.Globals.GetUrlRewriteExtension(), cateInsert.Title, cateInsert.MetaDescription);
				Globals.CreateSiteMap("~/sitemap.xml", urlRewriteCategory + DGSFramework.Globals.GetUrlRewriteExtension());
				Globals.CreateUrlList("~/urllist.txt", urlRewriteCategory + DGSFramework.Globals.GetUrlRewriteExtension());
				//data cache
				Cache.Remove("Category");

                //create db log
                CreateDBLog(null, null, TypeAction.Insert, "Tạo danh mục: " + cateInsert.Title, cateInsert.Description, "", "", "",
                        cateInsert.IsActive.Value.ToString(), cateInsert.IsTop.Value.ToString(), cateInsert.MetaKeywords, cateInsert.MetaDescription);

				//clear outputcache
				HttpResponse.RemoveOutputCacheItem("/Default.aspx");
				HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
				HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
				HttpResponse.RemoveOutputCacheItem("/Products.aspx");
				HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
				HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
				//redirect page
				Response.Redirect("Categories.aspx");
			}
			else
			{
				int cateID;
				int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
				var cateUpdate = entity.udv_Categories.Where(ca => ca.CateID == cateID).FirstOrDefault();
				if (cateUpdate != null)
				{
					if (ddlCategories.SelectedValue == cateUpdate.CateID.ToString())
					{
						lblMsg.Text = "Không cho phép danh mục muốn cập nhật có danh mục con là chính nó";
						lblMsg.ForeColor = System.Drawing.Color.Red;
						return;
					}
					string urlRewriteCategoryOld = Globals.CreateUrlRewriteCategory(ref entity, cateUpdate.CateID, true);
					string urlRewriteCategoryNew;
                    string oldTitle = cateUpdate.Title;
					cateUpdate.UpdatedDate = DateTime.Now;
					cateUpdate.UpdatedBy = Membership.GetUser().UserName;
					cateUpdate.Title = txtCateName.Text.Trim();
					cateUpdate.Title_en = txtCateName_en.Text.Trim();
					cateUpdate.ExternalLink = txtExternalLink.Text.Trim();
					cateUpdate.BlankExternalLink = chkBlankExternalLink.Checked;
					cateUpdate.Description = txtDesciption.Text;
					cateUpdate.Description_en = txtDesciption_en.Text;
					if (siuCateImage.HasNewImage == true)
					{
						Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + cateUpdate.ImageUrl));
						string fileNameImage = Globals.GetFileName(siuCateImage.SourceImageClientFileName);
						siuCateImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageCategories_Folder + fileNameImage);
						cateUpdate.ImageUrl = fileNameImage;
					}
					else if(siuCateImage.HasImage == false)
					{
						Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + cateUpdate.ImageUrl));
						cateUpdate.ImageUrl = "";
					}
					cateUpdate.ImageAlt = txtImageAlt.Text.Trim();
					cateUpdate.DisplayOrder = int.Parse(txtCateOrder.Text);
					cateUpdate.ParentID = int.Parse(ddlCategories.SelectedValue);
					cateUpdate.IsActive = chkIsActive.Checked;
                    cateUpdate.IsMenuBottom = chkIsActiveBottom.Checked;
					cateUpdate.IsTop = chkCateTop.Checked;
					cateUpdate.MetaDescription = txtMetaDescription.Text.Trim();
					cateUpdate.MetaKeywords = txtMetaKeywords.Text.Trim();
                    cateUpdate.MetaTitle = txtMetaTitle.Text.Trim();
                    cateUpdate.MetaOrther = HttpUtility.HtmlEncode(txtMetaOrther.Text);
					cateUpdate.PagingSize = int.Parse(txtPaging.Text);
					entity.SaveChanges();
					if (listImageNameUpload.Count > 0)
					{
						for (int i = 0; i < listImageNameUpload.Count; i++)
						{
							udv_Images imageCate = new udv_Images();
							imageCate.udv_Categories = cateUpdate;
							imageCate.ImageUrl = listImageNameUpload[i];
							imageCate.ImageAlt = listImageAlt[i];
							imageCate.Title = listImageTitle[i];
							imageCate.Title_en = listImageTitle_en[i];
							imageCate.Description = "";
							imageCate.Description_en = "";
							imageCate.AddedDate = DateTime.Now;
							entity.AddToudv_Images(imageCate);
							entity.SaveChanges();
						}
					}
					urlRewriteCategoryNew = Globals.CreateUrlRewriteCategory(ref entity, cateUpdate.CateID, true);
					cateUpdate.UrlRewrite = urlRewriteCategoryNew;
					entity.SaveChanges();
					Globals.UpdateROR("~/ror.xml", urlRewriteCategoryOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteCategoryNew + DGSFramework.Globals.GetUrlRewriteExtension(), cateUpdate.Title, cateUpdate.MetaDescription);
					Globals.UpdateSiteMap("~/sitemap.xml", urlRewriteCategoryOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteCategoryNew + DGSFramework.Globals.GetUrlRewriteExtension());
					Globals.UpdateUrlList("~/urllist.txt", urlRewriteCategoryOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteCategoryNew + DGSFramework.Globals.GetUrlRewriteExtension());
					//data cache
					Cache.Remove("Category");

                    //create db log
                    CreateDBLog(null, null, TypeAction.Update, "Cập nhật danh mục: " + oldTitle + " - " + cateUpdate.Title, cateUpdate.Description, "", "", "",
                            cateUpdate.IsActive.Value.ToString(), cateUpdate.IsTop.Value.ToString(), cateUpdate.MetaKeywords, cateUpdate.MetaDescription);

					//clear outputcache
					HttpResponse.RemoveOutputCacheItem("/Default.aspx");
					HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
					HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
					HttpResponse.RemoveOutputCacheItem("/Products.aspx");
					HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
					HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
					//redirect page
					Response.Redirect("Categories.aspx");
				}
				else
				{
					lblMsg.Text = "Danh mục muốn cập nhật không tồn tại";
					lblMsg.ForeColor = System.Drawing.Color.Red;
				}
			}
		}

		public List<string> GetImageTitle()
		{
			List<string> listTitle = new List<string>();
			for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
			{
				if (Request.Form["Title" + i.ToString()] != null)
				{
					listTitle.Add(Request.Form["Title" + i.ToString()].Trim());
				}
			}
			return listTitle;
		}

		public List<string> GetImageTitle_en()
		{
			List<string> listTitle = new List<string>();
			for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
			{
				if (Request.Form["Title_en" + i.ToString()] != null)
				{
					listTitle.Add(Request.Form["Title_en" + i.ToString()].Trim());
				}
			}
			return listTitle;
		}

		public List<string> GetImageAlt()
		{
			List<string> listAlt = new List<string>();
			for (int i = 0; i < int.Parse(hdfNumImage.Value); i++)
			{
				if (Request.Form["Alt" + i.ToString()] != null)
				{
					listAlt.Add(Request.Form["Alt" + i.ToString()].Trim());
				}
			}
			return listAlt;
		}

		public List<string> UploadAndGetImageName()
		{
			List<string> strFileName = new List<string>();
			HttpFileCollection hfc = Request.Files;
			if (hfc.Count > 0)
			{
				for (int i = 0; i < hfc.Count; i++)
				{
					HttpPostedFile hpf = hfc[i];
					if (hpf.FileName.Trim() != "")
					{
						string strFileNameTemp = Globals.GetFileName(hpf.FileName);
						strFileName.Add(strFileNameTemp);
						if (chkWatermarkImage2.Checked == false)
							hpf.SaveAs(Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + strFileNameTemp));
						else
						{
							XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
							XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
							Globals.CreateWatermark(hpf, Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + strFileNameTemp), Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value));
						}
					}
				}
			}
			return strFileName;
		}

		public void LoadListImageCate(int cateID)
		{
			List<udv_Images> listImageCate = entity.udv_Images.Where(ic => ic.udv_Categories.CateID == cateID).ToList();
			dtlImageCate.DataSource = listImageCate;
			dtlImageCate.DataBind();
		}

		[WebMethod]
		public static void DeleteImageCate(string ImageID)
		{
			DGSFrameworkEntities entity = new DGSFrameworkEntities();
			int imageID = int.Parse(ImageID);
			udv_Images imageCate = entity.udv_Images.Where(ic => ic.ImageID == imageID).FirstOrDefault();
			if (imageCate != null)
			{
				Globals.DelelteFile(HttpContext.Current.Server.MapPath(ConfigPaths.Path_ImageCategories_Folder_MapPath + imageCate.ImageUrl));
				entity.DeleteObject(imageCate);
				entity.SaveChanges();
			}
		}

		[WebMethod]
		public static void EditAttributeImageCate(string ImageID, string NewValue, string Attribute)
		{
			DGSFrameworkEntities entity = new DGSFrameworkEntities();
			int imageID = int.Parse(ImageID);
			udv_Images imageCate = entity.udv_Images.Where(ic => ic.ImageID == imageID).FirstOrDefault();
			string value = NewValue;
			string attribute = Attribute;
			if (imageCate != null)
			{
				if (attribute.Trim() == "title")
				{
					imageCate.Title = value;
				}
				else if (attribute.Trim() == "title_en")
				{
					imageCate.Title_en = value;
				}
				else if (attribute.Trim() == "alt")
				{
					imageCate.ImageAlt = value;
				}
				entity.SaveChanges();
			}
		}

		protected void chkWatermarkImage_CheckedChanged(object sender, EventArgs e)
		{
			if (chkWatermarkImage.Checked == true && siuCateImage.HasImage == false)
			{
				XDocument xDocWatermark = XDocument.Load(Server.MapPath(ConfigPaths.Path_Watermark_Xml));
				XElement xEImage = xDocWatermark.Descendants("img").FirstOrDefault();
				siuCateImage.PostProcessingFilter = new ImageWatermark(Server.MapPath(ConfigPaths.Path_ImageUpload_Folder_MapPath + xEImage.Value), System.Drawing.ContentAlignment.BottomRight);
			}
			else if (chkWatermarkImage.Checked == false && siuCateImage.HasImage == false)
			{
				siuCateImage.PostProcessingFilter = null;
			}
		}

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}